package jwt

import (
	"context"
	"fmt"
	"time"

	"server_1.0/api/internal/svc"
	"server_1.0/api/internal/types"
	"server_1.0/service/student/student"

	"github.com/golang-jwt/jwt"
	"github.com/zeromicro/go-zero/core/logx"
)

type RefreshJwtLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRefreshJwtLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RefreshJwtLogic {
	return &RefreshJwtLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RefreshJwtLogic) RefreshJwt() (resp *types.GetReps, err error) {
	nowID := fmt.Sprintf("%v", l.ctx.Value("userId"))
	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.JwtAuth.AccessExpire
	jwtToken, err := l.getJwtToken(l.svcCtx.Config.JwtAuth.AccessSecret, now, l.svcCtx.Config.JwtAuth.AccessExpire, nowID)
	if err != nil {
		return nil, err
	}
	Resp, err := l.svcCtx.StudentRpc.QueryID(l.ctx, &student.QueryIDReq{
		No: nowID,
	})
	if err != nil {
		return nil, err
	}
	sig := Resp.QRs[0]
	l.svcCtx.Redis.Set("loginUserId:"+nowID, sig.Name+";"+sig.Sex+";", time.Duration(accessExpire)*time.Second)
	return &types.GetReps{
		Code: 200,
		Msg:  "刷新成功",
		Data: map[string]interface{}{
			"accessToken":  jwtToken,
			"accessExpire": now + accessExpire,
			"refreshAfter": now + accessExpire/2,
		},
	}, nil
}

func (l *RefreshJwtLogic) getJwtToken(secretKey string, iat, seconds int64, userId string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
